package com.code.day02.utils;

import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionManager {
    private final static ThreadLocal<Connection> con = new ThreadLocal<>();
    public static Connection getConnection(){
        Connection conn = con.get();
        if(conn == null){
            conn = DruidUtils.getConnection();
            con.set(conn);
        }
        return conn;
    }

    public static void begin() throws SQLException {
        Connection conn = getConnection();
        conn.setAutoCommit(false);
    }

    public static void commit() throws SQLException {
        Connection conn = getConnection();
        conn.commit();
    }

    public static void rollback() throws SQLException {
        Connection conn = getConnection();
        conn.rollback();
    }

    public static void close() {
        Connection conn = getConnection();
        DruidUtils.close(conn, null, null);
        con.remove();
    }

}
